<?php

defined('_JEXEC') or die;
jimport('joomla.application.component.controllerform');

class App extends JControllerForm {
    /* constructor method */

    public function __construct($params = false) {
        //add your code here
    }

    public function getModel($name = '', $prefix = '', $asset = "", $client = 0) {
        $path = "";
        if (!$asset) {
            switch ($client) {
                case 1:
                    $path = JPATH_COMPONENT_SITE;
                    break;
                case 2:
                    $path = JPATH_COMPONENT_ADMINISTRATOR;
                    break;
                default :
                    $path = JPATH_COMPONENT;
            }
        } else {
            switch ($client) {
                case 1:
                    $path = JPATH_SITE;
                    break;
                case 2:
                    $path = JPATH_ADMINISTRATOR;
                    break;
                default :
                    $path = JPATH_BASE;
            }
            $path .= "/components/{$asset}";
        }
        require_once "{$path}/models/{$name}.php";
        return parent::getModel($name, $prefix);
    }

    function getWork($id = 0, $alias = NULL) {
        if ($id || $alias) {
            $db = JFactory::getDbo();
            $date = JFactory::getDate();
            $date = strtotime($date->toSql());
            $nearByProduct = array();
            $query = $db->getQuery(true);
            $query->select("a.*");
            $query->from('`#__works` AS a');

            $query->where('( a.state = 1 )');
            if ($id) {
                $query->where("( a.id = $id )");
            } elseif ($alias) {
                $alias = str_replace(":", "-", $alias);
                $query->where("( a.alias = '$alias' )");
            } else {
                return "";
            }
            $db->setQuery($query);
            $product = $db->loadObject();
            return $product;
        }
        return "";
    }

    function getWorkCategory($id = 0, $alias = NULL, $extension = "com_works") {
        $db = JFactory::getDbo();
        $date = JFactory::getDate();
        $date = strtotime($date->toSql());

        $query = $db->getQuery(true);
        $query->select("a.*");
        $query->from('`#__categories` AS a');

        $query->where('( a.published = 1 )');
        $query->where("( a.extension = '{$extension}' )");
        if ($id > 0 && $id) {
            $query->where("( a.id = {$id} )");
        }
        if ($alias) {
            $alias = str_replace(":", "-", $alias);
            $query->where("( a.alias = '{$alias}' )");
        }
        $db->setQuery($query);
        if ($id > 0 && $id) {
            return $db->loadObject();
        } else {
            return $db->loadObjectList();
        }
        return NULL;
    }

    function getWorkNearby($created = 0) {
        $db = JFactory::getDbo();
        $date = JFactory::getDate();
        $date = strtotime($date->toSql());
        $nearByProduct = array();
        $query = $db->getQuery(true);
        $query->select("a.*");
        $query->from('`#__works` AS a');

        $query->where('( a.state = 1 )');
        if ($created > 0 && $created) {
            $query->where("( a.created < $created )");
        }
        $query->order("a.created DESC");
        $db->setQuery($query);
        $nearByProduct[0] = $db->loadObject();
        $query->clear('where');
        $query->clear('order');
        $query->where('( a.state = 1 )');
        if ($created > 0 && $created) {
            $query->where("( a.created > $created )");
        }
        $query->order("a.created ASC");
        $db->setQuery($query);
        $nearByProduct[1] = $db->loadObject();
        return $nearByProduct;
    }

    static function make_title_furl($text) {
        //global $ibforums;
        //Charachters must be in ASCII and certain ones aint allowed
        $text = html_entity_decode($text);
        $text = preg_replace("/(ä|à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $text);
        $text = str_replace("ç", "c", $text);
        $text = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $text);
        $text = preg_replace("/(ì|í|î|ị|ỉ|ĩ)/", 'i', $text);
        $text = preg_replace("/(ö|ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $text);
        $text = preg_replace("/(ü|ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $text);
        $text = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $text);
        $text = preg_replace("/(đ)/", 'd', $text);
        $text = preg_replace("/(Ä|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $text);
        $text = str_replace("Ç", "C", $text);
        $text = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $text);
        $text = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $text);
        $text = preg_replace("/(Ö|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $text);
        $text = preg_replace("/(Ü|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $text);
        $text = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $text);
        $text = preg_replace("/(Đ)/", 'D', $text);
        //Remove HTML tags
        $text = strip_tags($text);
        $text = preg_replace("/<!--.*?-->/", "", $text);
        $text = preg_replace("/\/\/.*?\n/", "\n", $text);
        $text = preg_replace("/\/*.*?\*\//", "", $text);
        //Remove Quotes
        $text = str_replace(array('"', "'"), '', $text);
        $text = str_replace(array('”', "“"), '', $text);
        return $text;
    }

    /**
     * 
     * @param string $string Input string
     * @param int $start Default = 0
     * @param int $length Default = 55
     * @return type
     */
    function cut_string($string = "", $start = 0, $length = 55) {
        if ($string) {
            // Replace html ascii code
            $content = $this->remove_all_tags_html($string);
            if (strlen($content) > $length) {
                $arr_content = explode(" ", $content);
                $c1 = substr($content, $start, $length);
                $arr_c1 = explode(" ", $c1);
                if (count($arr_c1) > 1) {
                    if (isset($arr_content[count($arr_c1) - 1]) && $arr_c1[count($arr_c1) - 1] != $arr_content[count($arr_c1) - 1]) {
                        unset($arr_c1[count($arr_c1) - 1]);
                    }
                }
                $c1 = implode(" ", $arr_c1);
                return strlen($c1) < strlen($content) ? $c1 . "..." : $c1;
            } else {
                return $content;
            }
        }
        return $string;
    }

    function remove_all_tags_html($string = "") {
        // Convert from html ascii code to tag
        $string = html_entity_decode($string);

        // Disable warning error in DOM
        libxml_use_internal_errors(true);

        // Replace script
        $doc = new DOMDocument();
        $doc->loadHTML("<html><body>{$string}</body></html>");
        $xpath = new DOMXPath($doc);
        $mediaspace = $xpath->query("//div[@id='mediaspace']");
        if (isset($mediaspace->item(0)->nodeValue) && $mediaspace->item(0)->nodeValue) {
            $string = str_replace($mediaspace->item(0)->nodeValue, "", $string);
        }
        $embedcode = $xpath->query("//div[@class='embedcode']");
        if (isset($embedcode->item(0)->nodeValue) && $embedcode->item(0)->nodeValue) {
            $string = str_replace($embedcode->item(0)->nodeValue, "", $string);
        }
        $embeda = $xpath->query("//a[@class='embed_button']");
        if (isset($embeda->item(0)->nodeValue) && $embeda->item(0)->nodeValue) {
            $string = str_replace($embeda->item(0)->nodeValue, "", $string);
        }

        // Remove textarea content
        $string = preg_replace("(<textarea .*?>.*?</textarea>)is", "", $string);

        // Remove javascript
        $string = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $string);

        // Replace html tag
        $string = trim(strip_tags($string));
        return $string;
    }

    function getTagByItemElement($type_alias = "", $content_item_id = "") {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        // Select the required fields from the table.
        $query->select("DISTINCT a.*");

        $query->from('`#__tags` AS a');

        $query->join('LEFT', '#__contentitem_tag_map AS t ON t.tag_id = a.id');
        if ($type_alias) {
            $query->where("t.type_alias = '$type_alias'");
        }
        if ($content_item_id) {
            $query->where("t.content_item_id = '$content_item_id'");
        }
        try {
            $db->setQuery($query, 0, 5);
            $items = $db->loadObjectList();
        } catch (RuntimeException $e) {
            $this->setError($e->getMessage());
            return false;
        }
        return $items;
    }

    function checkIfExist($url) {
        $url = ltrim($url, "/");
        $url = str_replace(JURI::base(), "", $url);
        if (file_exists(JPATH_BASE . "/" . $url) && $url && is_file(JPATH_BASE . "/" . $url)) {
            return true;
        }
        return false;
    }

}
